package com.gp.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gp.common.utils.CookieUtils;
import com.gp.mapper.BaseCartMapper;
import com.gp.mapper.BaseUserMapper;
import com.gp.model.dto.BaseCartDto;
import com.gp.model.dto.ItemInfo;
import com.gp.model.entity.BaseCart;
import com.gp.model.entity.BaseUser;
import com.gp.service.IBaseCartService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 弓成龙
 * @since 2017-12-19
 */
@Service
public class BaseCartServiceImpl extends ServiceImpl<BaseCartMapper, BaseCart> implements IBaseCartService {

	@Autowired
	private BaseCartMapper cartMapper;
	@Autowired
	private BaseUserMapper userMapper;

	/**
	 * 定义cookie中购物车的名字，通过此名字获取购物车的json字符串
	 */
	private final static String COOKIE_CART_NAME = "cartInfo";

	@Override
	public boolean updateByUserID(ItemInfo itemInfo, HttpServletRequest reqeust) {
		// 根据 userid 修改购物车中的商品信息
		BaseUser user = (BaseUser) CookieUtils.obtainCurrentUser(reqeust);
		if (user == null) {
			return false;
		}
		return editCartItem(user.getId(), itemInfo);
	}

	/**
	 * 修改购物车中的商品
	 * 
	 * @param id
	 *            用户的id
	 * @param itemInfo
	 *            需要修改的商品信息
	 * @return 是否修改成功
	 */
	private boolean editCartItem(Long id, ItemInfo itemInfo) {
		// 目前只支持修改购物车中的商品的数量
		Wrapper<BaseCart> cart = new EntityWrapper<BaseCart>();
		cart.eq("userId", id);
		cart.eq("goodsId", itemInfo.getGoodsId());
		List<Object> list = cartMapper.selectObjs(cart);
		BaseCart dataCart = (BaseCart) list.get(0);
		dataCart.setNumber(itemInfo.getNumber());
		Integer flag = cartMapper.updateById(dataCart);
		return flag == 1;
	}

	@Override
	public boolean deleteCartItem(Long userid, Long goodsid) {
		Wrapper<BaseCart> wrapper = new EntityWrapper<>();
		wrapper.eq("userId", userid);
		wrapper.eq("goodsId", goodsid);
		Integer flag = cartMapper.delete(wrapper);
		return flag == 1;
	}

	@Override
	public boolean addCartItem(HttpServletRequest request, HttpServletResponse response, ItemInfo iteminfo) {
		// 持久化到数据库
		BaseUser user = (BaseUser) CookieUtils.obtainCurrentUser(request);
		if (user == null)
			return false;
		addCartDatabase(iteminfo, user.getId());
		return true;
	}

	/**
	 * 获取数据库中的购物车中的商品 
	 * 
	 * @return
	 */
	@Override
	public List<ItemInfo> selectAll(HttpServletRequest request) {
		List<ItemInfo> list = new ArrayList<ItemInfo>();
		BaseUser user = (BaseUser) CookieUtils.obtainCurrentUser(request);
		if (user != null) {
			list = cartMapper.selectAll(user.getId());
		}
		return list;
	}

	/**
	 * 添加商品到cookie中
	 * 
	 * @param request
	 * @param response
	 * @param iteminfo
	 *            商品基本信息
	 */
	private void addCartCookies(HttpServletRequest request, HttpServletResponse response, ItemInfo iteminfo) {
		List<ItemInfo> parseArray = obtainItemInfoListByCookie(request);
		parseArray = parseArray == null ? new ArrayList() : parseArray;
		parseArray.add(iteminfo);
		String str = JSON.toJSONString(parseArray);
		// 写回到response中
		CookieUtils.setCookie(response, COOKIE_CART_NAME, str);
	}

	/**
	 * 通过cookie 获取商品信息集合
	 * 
	 * @param request
	 * @return List<ItemInfo>
	 */
	private List<ItemInfo> obtainItemInfoListByCookie(HttpServletRequest request) {
		String value = CookieUtils.getCookieValue(request, COOKIE_CART_NAME);
		List<ItemInfo> parseArray = JSON.parseArray(value, ItemInfo.class);
		return parseArray;
	}

	/**
	 * 将购物车中的商品信息持久化到数据库
	 * 
	 * @param itemInfos
	 *            商品信息集合
	 */
	private void addCartDatabase(ItemInfo itemInfo, Long userId) {
		EntityWrapper<BaseCart> cart = new EntityWrapper<BaseCart>();
		cart.eq("goodsId", itemInfo.getGoodsId());
		cart.eq("userId", userId);
		List<BaseCart> list = cartMapper.selectList(cart);
		if (list != null && list.size() != 0) {
			BaseCart cart2 = list.get(0);
			cart2.setNumber(cart2.getNumber() + 1);
			cartMapper.updateById(cart2);
		} else {
			cartMapper.insert(new BaseCart(userId, itemInfo.getGoodsId(), itemInfo.getNumber(), new Date()));
		}
	}

	/**
	 * 重置cookies中的购物车信息
	 * 
	 * @param request
	 * @param response
	 * @param iteminfo
	 *            需要填充的购物车信息
	 */
	private void resetCartCookies(HttpServletRequest request, HttpServletResponse response, List<ItemInfo> iteminfos) {
		CookieUtils.setCookie(response, COOKIE_CART_NAME, JSON.toJSONString(iteminfos));
	}

	/*public List<BaseCartDto> selectCartList(HttpServletRequest request) {
		if (CookieUtils.isExistsCurrentUser(request)) {
			// 判断当前的用户是否登录，如果存在，从数据库中获取
			BaseUser user = (BaseUser) CookieUtils.obtainCurrentUser(request);
			Wrapper<BaseCart> wrapper = new EntityWrapper<BaseCart>();
			wrapper.eq("userid", user.getId());
			return cartMapper.selectCartList(wrapper);
		} else {
			// 如果当前的用户不存在，就从cookie中获取
			Cookie co = CookieUtils.getCookie(request, COOKIE_CART_NAME);
			if (null == co) {
				return null;
			}
			String goods = co.getValue();
			return JSON.parseArray(goods, BaseCartDto.class);
		}
	}*/

}
